<template>
  <div :style="`--visibilityValue:${disabledFlage ? 'hidden' : 'visible'}`">
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
  </div>
</template>

<script>
import vueQr from "vue-qr";
import { validDeviceCode, validMobile } from "@/utils/validate";
import { replaceDigit, replaceInteger, dealElectricity } from "@/utils/index";
export default {
  components: {
    vueQr,
  },
  props: {
    disabledFlage: {
      type: Boolean,
      default: false,
    },
  },
  dicts: [
    "device_type",
    "device_model",
    "wmeter_device_model",
    "special_energy_consumption_type",
  ],
  data() {
    return {
      apsForm: {
        formRef: "form",
        formData: {},
        labelWidth: "120px",
        formConfig: {
          formAttr: {
            // inline: true,
            "label-position": "right",
            size: "small",
            bsColumn: {
              col: 2,
              middle: true,
            },
            rules: {
              type: [
                {
                  required: true,
                  message: "请选择设备类型",
                  trigger: "change",
                },
              ],
              model: [
                {
                  required: true,
                  message: "请选择设备型号",
                  trigger: "change",
                },
              ],
              name: [
                { required: true, message: "请填写设备名称", trigger: "blur" },
              ],
              code: [
                {
                  required: true,
                  message: "请输入设备编码",
                  trigger: "blur",
                },
                // { validator: this.validCode },
              ],
              gatewayNo: [
                { required: true, message: "请填写网关号", trigger: "blur" },
              ],
              ct: [{ required: true, message: "请填写CT", trigger: "blur" }],
              ratedCurrent: [
                { required: true, message: "请填写额定电流", trigger: "blur" },
              ],
              ratedPower: [
                { required: true, message: "请填写额定功率", trigger: "blur" },
              ],
              warrantyPeriod: [
                { required: true, message: "质保期限不能为空" },
                { type: "number", message: "质保期限必须为数字值" },
              ],
              installTime: [
                {
                  required: true,
                  message: "请选择安装时间",
                  trigger: "change",
                },
              ],
              manufacturer: [
                { required: true, message: "请填写所属厂家", trigger: "blur" },
              ],
              installLocation: [
                {
                  required: true,
                  message: "请填写安装物理位置",
                  trigger: "blur",
                },
              ],
              installPerson: [
                { required: true, message: "请填写安装人员", trigger: "blur" },
              ],
              installPersonPhone: [
                {
                  required: true,
                  message: "请输入联系电话",
                  trigger: "blur",
                },
                { validator: this.validinstallPersonPhone },
              ],
              suggestChangeTime: [
                {
                  required: true,
                  message: "请选择建议更换日期",
                  trigger: "change",
                },
              ],
            },
          },
          properties: {
            type: {
              typeName: "el-select",
              label: "设备类型",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.device_type.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().type;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择设备类型",
                        value: valNum,
                        disabled: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("type", value);
                          // that.$refs?.form?.setFieldValue("model", "");
                          // if (value == 1) {
                          //   that.apsForm.formConfig.properties.caliber.display = false;
                          //   that.apsForm.formConfig.properties.cardNum.display = false;
                          // } else {
                          //   that.apsForm.formConfig.properties.caliber.display = true;
                          //   that.apsForm.formConfig.properties.cardNum.display = true;
                          // }
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: Number(value),
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            model: {
              typeName: "el-select",
              label: "设备型号",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.device_model.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().model;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择设备型号",
                        value: valNum,
                        disabled: that.disabledFlage,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          if (
                            value == 2 &&
                            that.$refs?.form?.getFieldsValue().type === 0
                          ) {
                            that.apsForm.formConfig.properties.gatewayNo.display = false;
                          } else {
                            that.apsForm.formConfig.properties.gatewayNo.display = true;
                          }
                          that.$refs?.form?.setFieldValue("model", value);
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: Number(value),
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            name: {
              label: "设备名称",
              typeName: "el-input",
              disabled: this.disabledFlage,
            },
            code: {
              label: "设备编码",
              typeName: "el-input",
              disabled: this.disabledFlage,
            },
            gatewayNo: {
              label: "网关号",
              typeName: "el-input",
              display: true,
              disabled: this.disabledFlage,
            },
            ct: {
              typeName: "el-input",
              label: "电流变比CT",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入CT"
                      value={this.$refs?.form?.getFieldsValue().ct}
                      clearable
                      onInput={(value) => this.keyFixAmount(value, "ct")}
                      disabled={this.disabledFlage}
                    ></el-input>
                  </div>
                );
              },
            },
            ratedCurrent: {
              typeName: "el-input",
              label: "额定电流",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入额定电流"
                      value={this.$refs?.form?.getFieldsValue().ratedCurrent}
                      clearable
                      onInput={(value) =>
                        this.keyFixAmount(value, "ratedCurrent")
                      }
                      disabled={this.disabledFlage}
                    >
                      <template slot="append">A</template>
                    </el-input>
                  </div>
                );
              },
            },
            ratedPower: {
              typeName: "el-input",
              label: "额定功率",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入额定功率"
                      value={this.$refs?.form?.getFieldsValue().ratedPower}
                      clearable
                      onInput={(value) =>
                        this.keyFixAmount(value, "ratedPower")
                      }
                      disabled={this.disabledFlage}
                    >
                      <template slot="append">W</template>
                    </el-input>
                  </div>
                );
              },
            },
            warrantyPeriod: {
              label: "质保期限(年)",
              typeName: "el-input-number",
              disabled: this.disabledFlage,
            },
            installTime: {
              label: "安装时间",
              typeName: "el-date-picker",
              type: "date",
              "value-format": "yyyy-MM-dd",
              placeholder: "请选择安装时间",
              disabled: this.disabledFlage,
            },
            manufacturer: {
              label: "所属厂家",
              typeName: "el-input",
              disabled: this.disabledFlage,
            },
            installLocation: {
              label: "安装位置描述",
              typeName: "el-input",
              disabled: this.disabledFlage,
            },
            installPerson: {
              label: "安装人员",
              typeName: "el-input",
              disabled: this.disabledFlage,
            },
            installPersonPhone: {
              label: "联系电话",
              typeName: "el-input",
              disabled: this.disabledFlage,
            },
            suggestChangeTime: {
              typeName: "el-date-picker",
              type: "date",
              label: "建议更换日期",
              "value-format": "yyyy-MM-dd",
              placeholder: "请选择建议更换日期",
              disabled: this.disabledFlage,
            },
            qrCode: {
              label: "二维码",
              render: (h) => {
                let that = this;
                let a, b, style;
                let value = this.$refs?.form?.getFieldsValue().qrCode;
                if (value) {
                  a = <vueQr text={value} size={80} margin={0}></vueQr>;
                  b = "";
                  // b = (
                  //   <el-button size="small" onClick={that.downCode}>
                  //     保存
                  //   </el-button>
                  // );
                } else {
                  a = "二维码加载失败";
                  b = "";
                }
                style = {
                  display: "flex",
                  alignItems: "end",
                };
                return (
                  <div style={style}>
                    <div>{a}</div>
                    <div style="margin-left:10px">{b}</div>
                  </div>
                );
              },
            },
            specialEnergyConsumptionType: {
              label: "用能类型",
              display: !this.disabledFlage,
              render: (h) => {
                let that = this;
                let valNum =
                  that.$refs?.form?.getFieldsValue()
                    .specialEnergyConsumptionType;
                let showArr = [];
                if (valNum && valNum.length > 0) {
                  valNum.map((tig) => {
                    let a = (
                      <dict-tag
                        options={this.dict.type.special_energy_consumption_type}
                        value={tig}
                      />
                    );
                    showArr.push(a);
                  });
                }
                return h("div", showArr);
                // return <div>{showArr}</div>;
              },
            },
            installationPicture: {
              bsColumn: {
                col: 1,
                middle: true,
              },
              typeName: "ImageUpload",
              limit: 2,
              fileSize: 5,
              accept: "image/*",
              showPlus: !this.disabledFlage,
              isShowTip: !this.disabledFlage,
              // fileBigness: "311*140px",
              label: "安装现场图片",
              disabled: this.disabledFlage,
            },
          },
        },
      },
    };
  },
  created() {},
  mounted() {
    this.$refs?.form?.setFieldValue("type", 0);
  },
  methods: {
    validinstallPersonPhone(rule, value, callback) {
      if (!validMobile(value)) {
        callback("联系电话格式不正确");
      } else {
        callback();
      }
    },
    validCode(rule, value, callback) {
      if (!validDeviceCode(value)) {
        callback("设备编码格式不正确");
      } else {
        callback();
      }
    },
    getfromData() {
      const data = {
        ...this.$refs.form.getFieldsValue(),
      };
      data.specialEnergyConsumptionType = undefined;
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$emit("formDatagive", data);
        } else {
          return false;
        }
      });
    },
    resetForm() {
      this.$refs["form"].resetFields();
    },
    setForm(data) {
      this.$refs?.form?.setFieldsValue(data);
    },
    keyFixAmount(value, key) {
      if (key == "caliber" || key == "ratedPower") {
        this.$refs?.form?.setFieldValue(key, replaceInteger(value));
      } else {
        this.$refs?.form?.setFieldValue(key, replaceDigit(value, 2));
      }
    },
    downCode() {
      let name = new Date().getTime();
      // let imgsrc =
      //   "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2Fe23ef8a7-ca1f-471d-8553-ca5bf429bbc1%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1691049049&t=f176bc4e4c2fe6cb82b0c99e6a8c85c0";
      let imgsrc = this.$refs?.form?.getFieldsValue().qrCode;
      var image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute("crossOrigin", "anonymous");
      image.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;

        var context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        var url = canvas.toDataURL("image/png");
        var a = document.createElement("a");
        // 创建一个单击事件
        var event = new MouseEvent("click");
        a.download = name;
        a.href = url;
        // 触发a的单击事件
        a.dispatchEvent(event);
      };
      image.src = imgsrc;
      this.$message.success("下载成功");
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-upload-list--picture-card .el-upload-list__item-status-label {
  visibility: var(--visibilityValue);
}
</style>
